﻿using XW.Logging;
using XW.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using XW.Core;

namespace XW.Web.Framework.Permissions
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
    public class PermissionAttribute : Attribute, IAuthorizationFilter
    {
        private ILog L = LogProvider.GetCurrentClassLogger(); 
        public string Name { get; set; }

        public PermissionAttribute(string name)
        {
            Name = name;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var permissionHandlerProvider = context.HttpContext.RequestServices.GetRequiredService<IPermissionHandlerProvider>();
            
            var permissionHandler = permissionHandlerProvider.GetHandler(context);
            var hasPermission = permissionHandler.HasPermission(context.HttpContext.User, this.Name);
            // 用户Id
            var userid = CommonHelper.ToInt64(context.HttpContext.User.FindFirstValue(JwtTokenConst.JWT_USER_ID));
            this.L.Debug("检查用户[{1}],权限结果：{0}", hasPermission, userid);
            if (hasPermission == false)
            {
                context.Result = new ForbiddenResult(Name);
            }
        }
    }
}
